package com.quiz.file.controller;

import com.quiz.common.exception.ServiceException;
import com.quiz.file.domain.model.FileInfo;
import com.quiz.file.service.IFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 重定向控制器
 *
 * @author ahuan
 */
@Slf4j
@Controller
@RequiredArgsConstructor
public class RedirectController {

    private final IFileService baseService;

    @RequestMapping(method = RequestMethod.GET, value = "/pdf-preview")
    public void pdfPreview(@RequestParam("fileId") Long fileId, Model model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FileInfo fileInfo = baseService.getFileById(fileId);
        File file = new File(fileInfo.getFilePath());

        if (!file.exists()) {
            throw new ServiceException("文件不存在");
        }

        model.addAttribute("fileUrl", file.toURI().toString());
        log.info("=========>PDF文件预览成功，文件名：{}", file.toURI().toString());
        request.getRequestDispatcher("/templates/html/pdfPreview.html").forward(request,response);
    }
}
